from django.shortcuts import render
from rest_framework.views import APIView
import re
from .serializer import RoleModelSerializer, UserModelSerializer
from .models import Role,User
from rest_framework.response import Response
# Create your views here.

class LoginView(APIView):


    # 注册
    def post(self,request):
        # 获取网页提交数据
        name = request.data.get('name')   # .data只有继承APIView才可以使用
        # 获取数据库内容，用来判断角色  是否存在
        role_obj = Role.objects.filter(name=name)
        # 判断角色是否存在
        if role_obj :
            return Response({'msg':'角色存在','code':400})
        role_serializer = RoleModelSerializer(data=request.data)
        if role_serializer.is_valid():
            role_serializer.save()
            return Response({'msg':'添加成功' , 'code' : 200})
        else:
            return Response({'error':role_serializer.errors})



class RegisterView(APIView):

    def post(self,request):
        user_name = request.data.get('user_name')
        password1 = request.data.get('password1')
        password2 = request.data.get('password2')
        phone = request.data.get('phone')
        email = request.data.get('email')
        role_id = request.data.get('role')

        if not all([user_name,password1,password2,phone,email,role_id]):
            return Response({'msg':'数据不完整' , 'code' :400})

        phone_re = re.compile(r'^1(3\d|4[4-9]|5[0-35-9]|6[67]|7[013-8]|8[0-9]|9[0-9])\d{8}$')
        if not re.search(phone_re, phone):
            return Response({'msg': '手机号不符合规范', 'code': 400})

        # 获取数据库中数据，用来判断用户是否存在
        user_obj = User.objects.filter(user_name=user_name)

        # 判断两次密码
        if password1 == password2:
            # 反序列化添加
            user_data = {
                'user_name': user_name, 'password' :make_password(password1),
                'phone':phone , 'email':email,'role':role_id}
            user_serializer = UserModelSerializer(data=user_data)
            # 校验
            if user_serializer.is_valid():
                user_serializer.save()
                # 发邮件
                # 异步
                user_info = {'user_id' : user_serializer.data.get('id')}
                # 把用户信息进行序列化
                # token = token_serializer.dump





